<?php
declare (strict_types = 1);

namespace app\service\logic\backend\site;

use app\exception\LogicException;
use app\facade\HasherFacade;
use app\model\communal\AdminModel;

final class SiteService
{
    /**
     * 账号密码登录
     *
     * @param $params
     * @return array
     * @throws LogicException
     */
    public function login($params)
    {
        // 检测下
        $admin = AdminModel::where(['relation_type' => $params['relation_type']])
            ->where('account', $params['account'])->findOrEmpty();
        if ($admin->isEmpty()) {
            throw new LogicException('账号不存在');
        }
        unset($params['relation_type']);
        $token = auth('backend')->attempt($params);
        $admin = auth('backend')->getLastAttempted();
        return [
            'user' => $admin,
            'token' => $token
        ];
    }

    /**
     * 验证码登录
     *
     * @param $params
     * @return array
     * @throws LogicException
     */
    public function captcha($params)
    {
        $admin = AdminModel::where('mobile', $params['mobile'])->findOrEmpty();

        if ($admin->isEmpty()) {
            throw new LogicException(lang('backend.mobile not found'));
        }

        $token = auth('backend')->login($admin);
        return [
            'user' => $admin,
            'token' => $token
        ];
    }

    /**
     * 修改密码
     *
     * @param $params
     * @return bool
     */
    public function password($params)
    {
        $adminModel = AdminModel::where('mobile', $params['mobile'])->findOrFail();
        $params['password'] = HasherFacade::make($params['password']);
        $result = $adminModel->allowField(['password'])->save($params);

        // 禁用
        event('AfterPassword', ['id' => $adminModel['id']]); // 可队列
        return $result;
    }
}
